<template>
  <div class="cart-container">
    <h2>我的购物车</h2>

    <div v-if="cartItems.length === 0" class="empty-cart">
      <el-empty description="购物车是空的" />
      <el-button type="primary" @click="$router.push('/products')">去购物</el-button>
    </div>

    <div v-else>
      <el-table :data="cartItems" style="width: 100%">
        <el-table-column label="商品" min-width="400">
          <template #default="{ row }">
            <div class="product-info">
              <img :src="row.product?.imageUrl || '/images/default-product.jpg'" class="product-image" />
              <div class="product-details">
                <h3>{{ row.product?.name || '商品名称' }}</h3>
                <p class="description">{{ row.product?.description || '商品描述' }}</p>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="单价" width="120">
          <template #default="{ row }">
            <span class="price">¥{{ row.product?.finalPrice || row.product?.birthdayPrice || row.product?.memberPrice || row.product?.price || 0 }}</span>
          </template>
        </el-table-column>

        <el-table-column label="数量" width="200">
          <template #default="{ row }">
            <el-input-number
                v-model="row.quantity"
                :min="1"
                :max="99"
                @change="(value) => handleQuantityChange(row.id, value)"
            />
          </template>
        </el-table-column>

        <el-table-column label="小计" width="120">
          <template #default="{ row }">
            <span class="subtotal">¥{{ ((row.product?.finalPrice || row.product?.birthdayPrice || row.product?.memberPrice || row.product?.price || 0) * row.quantity).toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
                type="danger"
                size="small"
                @click="handleRemove(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-footer">
        <div class="cart-summary">
          <span>总计: </span>
          <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
        </div>
        <div class="cart-actions">
          <el-button @click="handleClear">清空购物车</el-button>
          <el-button type="primary" @click="handleCheckout">结算</el-button>
        </div>
      </div>
    </div>

    <!-- 结算对话框 -->
    <el-dialog v-model="checkoutDialogVisible" title="确认订单" width="500px">
      <el-form :model="orderForm" label-width="100px">
        <el-form-item label="收货地址">
          <el-input v-model="orderForm.address" />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="orderForm.contactPhone" />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="orderForm.paymentMethod">
            <el-option label="支付宝" value="ALIPAY" />
            <el-option label="微信支付" value="WECHAT" />
            <el-option label="银行卡" value="CREDIT_CARD" />
          </el-select>
        </el-form-item>
        <el-form-item label="运送方式">
          <el-select v-model="orderForm.shippingMethod">
            <el-option label="快递" value="EXPRESS" />
            <el-option label="标准配送" value="STANDARD" />
            <el-option label="自提" value="PICKUP" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="checkoutDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder" :loading="submitting">
            确认下单
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCartList, updateCartItem, removeCartItem, clearCart, checkoutCart } from '@/api/cart'

const cartItems = ref([])
const checkoutDialogVisible = ref(false)
const submitting = ref(false)

const orderForm = ref({
  address: '',
  contactPhone: '',
  paymentMethod: '',
  shippingMethod: ''
})

const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    const unitPrice = item.product?.finalPrice || item.product?.birthdayPrice || item.product?.memberPrice || item.product?.price || 0;
    return total + unitPrice * item.quantity;
  }, 0)
})

onMounted(async () => {
  await loadCartItems()
})

const loadCartItems = async () => {
  try {
    const res = await getCartList()
    cartItems.value = res.data || []
  } catch (error) {
    console.error(error)
    ElMessage.error('获取购物车数据失败')
  }
}

const handleQuantityChange = async (id, quantity) => {
  try {
    await updateCartItem(id, quantity)
    ElMessage.success('更新成功')
  } catch (error) {
    console.error(error)
    ElMessage.error('更新失败')
    await loadCartItems() // 重新加载以恢复正确数量
  }
}

const handleRemove = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      type: 'warning'
    })
    await removeCartItem(id)
    ElMessage.success('删除成功')
    await loadCartItems()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('删除失败')
    }
  }
}

const handleClear = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      type: 'warning'
    })
    await clearCart()
    ElMessage.success('购物车已清空')
    await loadCartItems()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('清空失败')
    }
  }
}

const handleCheckout = () => {
  checkoutDialogVisible.value = true
}

const submitOrder = async () => {
  submitting.value = true
  try {
    // 使用购物车结算功能
    await checkoutCart(orderForm.value)
    ElMessage.success('下单成功')
    checkoutDialogVisible.value = false
    await loadCartItems()
  } catch (error) {
    console.error(error)
    ElMessage.error('下单失败')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.cart-container {
  padding: 20px;
}

.empty-cart {
  text-align: center;
  padding: 40px 0;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.product-details h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.description {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.price, .subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.cart-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
}

.cart-summary {
  font-size: 16px;
}

.total-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-left: 8px;
}

.cart-actions {
  display: flex;
  gap: 10px;
}
</style> 